<?php
/**
 * 用户游戏搜索记录处理模型
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/10
 * Time: 10:00
 */

class Searchlog_model extends CI_Model
{
    var $_table_name = 'search_log';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 添加搜索记录
     * @param string $user_openid
     * @param string $search_content
     * @param int $result_count
     */
    public function add_search_log($user_openid, $search_content, $result_count)
    {

        $arr_search_log = array(
            'user_openid' => $user_openid,
            'search_content' => $search_content,
            'result_count' => $result_count,
            'search_time' => time()
        );

        $this->db->insert($this->_table_name, $arr_search_log);
    }

    /**
     * 根据条件统计汇总搜索记录，数据项为关键词、搜索次数、搜索结果数
     * @param int $start_time
     * @param int $end_time
     * @param bool $order_result_count_first
     * @param int $num 设置返回的数据条数
     * @return mixed
     */
    public function get_top_search($start_time=0, $end_time=0, $order_result_count_first=false, $num=0)
    {

        $end_time === 0 && $end_time = time();
        $start_time ===0 && $start_time = $end_time - 3600*24*7;

        $sql='select search_content,count(search_content) as search_count,avg(result_count) as game_num 
               from '. $this->db->dbprefix($this->_table_name). " 
               where search_time>=$start_time AND search_time<=$end_time 
               GROUP BY search_content";

        if($order_result_count_first === false){
            $sql = $sql . ' ORDER BY search_count DESC, result_count DESC';
        }else{
            $sql = $sql . ' ORDER BY result_count ASC, search_count DESC';
        }

        if($num!==0){
            $sql = $sql . ' limit 0,'.$num;
        }

        $query = $this->db->query($sql);
        $result = $query->result_array();
        return $result;
    }

    /**
     * 统计汇总指定用户的搜索记录，返回数据项为搜索内容、搜索次数
     * @param $user_openid
     * @param int $start_time
     * @param int $end_time
     * @param int $num
     * @return mixed
     */
    public function summary_by_user($user_openid, $start_time=0, $end_time=0, $num=0)
    {
        $end_time === 0 && $end_time = time();
        $start_time ===0 && $start_time = $end_time - 3600*24*7;

        $sql='select search_content,count(search_content) as search_count 
               from '. $this->db->dbprefix($this->_table_name). " 
               where user_openid='$user_openid' and search_time>=$start_time AND search_time<=$end_time 
               GROUP BY search_content
               ORDER BY search_count DESC";

        if($num!==0){
            $sql = $sql . ' limit 0,'.$num;
        }

        $query = $this->db->query($sql);
        $result = $query->result_array();
        return $result;
    }

}